package eece261.dChatter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public class ChatWindow extends Activity{
	
	private String                        username_;
	private InetSocketAddress             ip_address_;
	private EditText                      chat_edit_;
	private TextView                      text_log_;
	private MulticastSocket               socket_;
	private BlockingQueue<dChatMessage>	  msg_queue_;
	private dChatListener             	  listener_;
	private dChatSender                   sender_;
	private String						  Last_Msg;
	private InetAddress					  local_address_;
	private int                           User_Code_;
	private ScrollView					  Scroll_;
	@Override    
	public void onCreate(Bundle savedInstanceState) {
        
		super.onCreate(savedInstanceState);
        setContentView(R.layout.chatwindow);
        
        Bundle extras = getIntent().getExtras();
      	username_     = extras.getString("username");
       	ip_address_   = new InetSocketAddress(extras.getString("ip"), extras.getInt("port"));
       	
        chat_edit_    = (EditText)  findViewById(R.id.ChatEdit); 
        Scroll_       = (ScrollView)findViewById(R.id.ScrollView01);
        text_log_ 	  = (TextView)  findViewById(R.id.ChatView);
    	try {
			socket_	  = new MulticastSocket(ip_address_);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
		text_log_.append("IP: " + ip_address_.getAddress() + "  Port: " + extras.getInt("port"));
		
    	msg_queue_	  = new LinkedBlockingQueue<dChatMessage>();
    	
    	try {
			socket_.joinGroup(ip_address_.getAddress());
		} catch (IOException e) {
			e.printStackTrace();
		}
		//Obtain your UserID
		try {
    	    Socket socket = new Socket("www.google.com",80);
    	    Log.i("", socket.getLocalAddress().toString());
    	    local_address_ = socket.getLocalAddress();
        	this.User_Code_ = this.getUserNumber();
    	} catch (Exception e) {
    	    Log.i("", e.getMessage());
    	}
    	//Start listener and sender threads
    	listener_ 	  = new dChatListener(socket_, text_log_, Scroll_);
    	sender_		  = new dChatSender  (socket_, msg_queue_);
    	
    	(new Thread(listener_)).start();
    	(new Thread(sender_  )).start();
    	
    	Last_Msg = username_+ ": joined the chat.";
    	listener_.setUserNumber(this.User_Code_);
    	msg_queue_.add(new dChatMessage(Last_Msg,0,ip_address_,User_Code_));        		
        
    	
    	final Button sendButton = (Button)findViewById(R.id.SendButton);
        sendButton.setOnClickListener(new View.OnClickListener() {
        	
        	public void onClick(View v) {
        		String temp = username_+ ": " + chat_edit_.getText().toString();
        		Last_Msg = listener_.getLastMSG();
        		msg_queue_.add(new dChatMessage(temp,Last_Msg,0,ip_address_,User_Code_));
            }
        });
	}
	
    @Override
    protected void onStart() {
    	super.onStart();
    	
    }
    public int getUserNumber()
    {
    	String adrstr = this.local_address_.getHostAddress();
    	int b = 0;
    	int count = 0;
    	int place = 0;
    	while(count < 3)
    	{
    		if(adrstr.charAt(place) == '.')
    		{
    			count++;
    		}
    		place++;
    	}
    	String clear = "";
    	for(int ii=place;ii<adrstr.length();ii++)
    	{
    		clear = clear + adrstr.charAt(ii);
    	}
    	b = Integer.parseInt(clear);
    	return b;
    }
}